import React, { Component } from 'react';
import { hashHistory } from 'react-router';
import { List, InputItem, Toast, Modal, Picker, Icon } from 'antd-mobile';
import { createForm } from 'rc-form';
import { loginApi } from 'js/api/login';
import api from 'js/api/index';
import userData from 'js/core/userData';
import './login.scss';
import { StringUpdater } from 'js/lib/string_update';
import { SubViewLink } from 'views/component/subViewLink/subViewLink';
import 'js/lib/base64';
import { i18n } from 'js/core/i18n';

class Login extends Component {
	constructor() {
		super()
		let user = userData.get();
		this.state = {
			languageList: null,
			language: user.Language,
			languageId: null,
			err: {}
		}
	}
	componentDidMount() {
		this.props.form.setFieldsValue({
			Account: window.localStorage.getItem('Account'),
			Pwd: window.localStorage.getItem('Pwd'),
		})

		api('/Language/getlanguagelist').then((data) => {
			let user = userData.get(), language;
			let langaugeId = user.langaugeId || 1
			let languageList = data.result.map(item => {
				let d = {};
				d.label = item.languageDesc;
				d.value = item.languageId;
				d.name = item.Language;
				if (langaugeId === item.languageId) {
					language = item.languageDesc
				}
				return d;
			})
			this.setState({ languageList: [languageList], languageId: [langaugeId], language: language })
		});
	}
	submit = (e) => {
		e.stopPropagation();
		e.preventDefault();
		this.props.form.validateFields((err, values) => {
			if (!err) {
				let value = {};
				value.Account = StringUpdater.mode1.update(window.BASE64.encoder(values.Account));
				value.Pwd = StringUpdater.mode1.update(window.BASE64.encoder(values.Pwd));
				window.localStorage.setItem('Account', values.Account);
				window.localStorage.setItem('Pwd', values.Pwd);
				Toast.loading(null, 15)
				value.language = window.localStorage.getItem('defaultLanguage');
				value.languageId = this.state.languageId;
				if (!value.language || value.language === 'undefined') {
					value.language = 'zh-CN'
				}
				api('/Home/Login', value, 'POST').then((res) => {
					if (res.code === 1) {
						Toast.hide()
						userData.set(res);
						window.localStorage.setItem('defaultLanguage', res.Language);
						i18n.setLanguageData(res.Language, res.Lang);
						api('/Home/MenuList').then((res) => {
							let power = [];
							res.result.forEach(item => {
								power.push(item.id);
							});
							userData.setKey('power', power);
							window.location.href = "#/";
						})
					} else if (res.code === 0) {
						Toast.hide()
						Toast.fail(res.message, 2);
						return
					}
				});
				return false;
			} else {
				this.setState({ err: err || {} });
			}
		});
		return false;
	}
	onOk = (value) => {
		value = value[0];
		let data = this.state.languageList[0].find((item => item.value === value));
		this.setState({ language: data.label, languageId: [value] })
		this.setlanguage(value, data.name);
	}
	setlanguage = (languageId, Language) => {

		// api('/Language/setlanguage', { languageId: languageId, Language: Language }, 'POST').then((res) => {
		userData.setKey('Language', Language);
		userData.setKey('langaugeId', languageId);
		window.localStorage.setItem('defaultLanguage', Language);
		i18n.setLanguage(Language);
		window.location.replace(window.location.href.split('?')[0] + '?m=' + new Date().getTime());
		// });
	}
	render() {
		let { getFieldProps, setFieldsValue } = this.props.form;
		let { err } = this.state;
		let { languageList, languageId, language } = this.state;
		return <div id="login-box">
			<div className="setBox"
				onClick={() => {
					Modal.prompt('输入api地址', <div>已经绑定的api: <br /> {window.localStorage.getItem('baseUrl') || window.defaultApi}</div>,
						[
							{ text: '取消' },
							{
								text: '确定',
								onPress: value => { window.localStorage.setItem('baseUrl', value); }
							},
						], 'default', null, ['例如:' + window.defaultApi])
				}}
			></div>
			<div className="login-container">
				<div className="logo"></div>

				<InputItem
					className="mb20"
					{...getFieldProps('Account', {
						rules: [
							{ required: true },
						],
					})}
					placeholder={i18n.get('输入用户名')}
					error={err.Account}
					onFocus={() => { delete err.Account; this.setState({}); }}
				> <div className="icon-box username"></div>
				</InputItem>
				<InputItem
					className="mb20"
					type="password"
					{...getFieldProps('Pwd', {
						rules: [{ required: true }],
					})}
					error={err.Pwd}
					placeholder={i18n.get('输入密码')}
					onFocus={() => { delete err.Pwd; this.setState({}); }}
				><div className="icon-box password"></div></InputItem>

				<div className="lang-item flex-center">
					{languageList && <div className="flex-g-1 text-left"><Picker extra={i18n.get("请选择")} okText={i18n.get("确定")} dismissText={i18n.get("取消")} value={languageId} title={i18n.get("语言")} cascade={false} data={languageList} cols={1} onOk={this.onOk}>
						<div className="flex-center">
							<div className="flex-g-1 pl20">{language}</div><Icon type="right" color="#000" size="md" />
						</div>
					</Picker></div>}
				</div>
				<div className="login-btn">
					<button type="submit" className="btn btn-primary login-sty" onClick={this.submit}>{i18n.get('登录')}</button>
					<div className="flex jc-between">
						<SubViewLink moduleName="register" title={i18n.get("注册用户")}>{i18n.get('注册用户')}</SubViewLink>
						<SubViewLink moduleName="forget" title={i18n.get("忘记密码")}>{i18n.get('忘记密码')}</SubViewLink>
					</div>
				</div>
				<div className="edition">{i18n.get("版本号")}:1.0.32</div>

			</div>
		</div >;
	}
}

export default createForm()(Login);
